<script setup>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { ElMessageBox, ElMessage } from 'element-plus'
import lodash from 'lodash'
import router from '@/router'


// 创建 API 客户端实例
const apiClient = axios.create({
  baseURL: 'http://localhost:8089', // 根据实际后端地址修改
  timeout: 10000,
})

// 添加请求拦截器，如果需要token认证
apiClient.interceptors.request.use(
    config => {
      // 从localStorage获取token并添加到请求头
      const token = localStorage.getItem('token');
      if (token) {
        config.headers.Authorization = token;
      }
      return config;
    },
    error => {
      return Promise.reject(error);
    }
);

// 添加响应拦截器处理通用逻辑
apiClient.interceptors.response.use(
    response => {
      // 直接返回数据
      return response.data;
    },
    error => {
      // 统一处理错误
      if (error.response && error.response.status === 401) {
        // 未授权，跳转到登录页
        ElMessage.error('认证失败，请重新登录');
        localStorage.removeItem('token');
        router.push('/login');
      } else {
        ElMessage.error('请求失败: ' + (error.response?.data?.msg || error.message));
      }
      return Promise.reject(error);
    }
);

// 获取座位价格信息的函数
const getSeatPrice = async (seatid) => {
  if (!seatid) return '未知价格';
  try {
    const response = await apiClient.get(`/seatprice/getbyseatid/${seatid}`);
    if (response.data && response.code === 200) {
      return response.data.price || '无价格';
    }
    return '无价格';
  } catch (error) {
    console.error('获取座位价格失败:', error);
    return '价格获取失败';
  }
};

const seatInfo = ref(null)
async function getseat(){
  try {
    const response = await apiClient.get(`/seat/all`);
    seatInfo.value = response.data;
    console.log(seatInfo.value);
    return seatInfo.value;
  } catch (error) {
    console.error("获取用户信息失败:", error);
    return null;
  }
}


const tableData=ref([]);

const  total=ref(0);
//定义对话框的显示状态
const editWinVisible = ref(false);
//查询数据
const searchObj=ref({
  current:1,
  limit:5,
  total:0,
  concertid:'',
  area:'',
  count:'',
  capacity:'',
  status:'',
});
//要修改或者新增的数据
const obj=ref({});

const search = async () => {
  try {
    // 使用网关进行分页查询
    const params = {
      current: searchObj.value.current,
      limit: searchObj.value.limit,
      concertid: searchObj.value.concertid,
      area: searchObj.value.area,
      count: searchObj.value.count,
      capacity: searchObj.value.capacity,
      status: searchObj.value.status
    };
    console.log('请求参数:', params);
    const response = await apiClient.get('/seat/page', { params });
    console.log('接口响应:', response); // 查看响应结构
    if (response.data && response.data.records) {
      // 处理每条记录，获取价格信息
      const recordsWithPrices = await Promise.all(response.data.records.map(async (record) => {
        // 如果后端没有直接返回价格，我们需要单独获取
        if (record.price) {
          // 后端已经返回了价格
          return record;
        } else if (record.id) {
          // 后端只返回了座位ID，需要我们自己获取价格
          const price = await getSeatPrice(record.id);
          return { ...record, price };
        } else {
          // 没有座位ID
          return { ...record, price: '未知价格' };
        }
      }));

      tableData.value = recordsWithPrices;
      total.value = response.data.total || 0;
    } else {
      tableData.value = response.data.records || [];
      total.value = response.data.total || 0;
    }
  } catch (error) {
    console.error("获取用户列表失败:", error);
    ElMessage.error('获取用户列表失败');
    tableData.value = [];
    total.value = 0;
  }

}
//页面加载后要挂载的数据
onMounted(async () => {
  await getseat();
  await search();
});
//定义方法

const handleSizeChange = () => {
  search();
}
const handleCurrentChange = () => {
  search();
}
const handleSearch = async () => {
  searchObj.value.current=1
  search();
}
const handleAdd = () => {
  // 初始化新增对象，包含所有必要字段
  obj.value = {
    concertid:{'concertTitle':''},
    area:'看台',
    count:'',
    capacity:'',
    status: '0',  // 默认启用状态
    // 其他需要的字段
  };
  editWinVisible.value = true;
}

const editCancel = () => {
  obj.value = {};//清空数据
  editWinVisible.value = false;//关闭对话框
}
const editCommit = async () => {
  // await api.edit(obj.value);//提交修改数据
  // search();//刷新表格
  // editWinVisible.value = false;//关闭编辑对话框
  try {
    if (obj.value.id) {
      // 编辑操作
      await apiClient.put('/seat/edit', obj.value);
      ElMessage.success('编辑成功');
    } else {
      // 新增操作
      await apiClient.post('/seat/add', obj.value);
      ElMessage.success('新增成功');
    }
    search(); // 刷新表格
    editWinVisible.value = false; // 关闭编辑对话框
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error('操作失败: ' + (error.response?.data?.msg || error.message));
    // 可以添加 Element Plus 的消息提示
    // ElMessage.error('操作失败');
  }
}

const handleEdit = (index, row) => {
  obj.value=lodash.clone(row);
  editWinVisible.value = true;
  console.log(index, row)
}
const handleDelete = (index, row) => {
  ElMessageBox.confirm(
      '确认删除该行数据吗?',
      '删除提示',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'error',
      }
  )
      .then(async() => {
        try {
          await apiClient.delete(`/seat/deleteSeat/${row.id}`);
          ElMessage.success('删除成功');
          //重新加载数据
          //设置从第一页开始查询
          searchObj.value.current = 1;
          search();
        } catch (error) {
          ElMessage.error('删除失败: ' + (error.response?.data?.msg || error.message));
        }
      })
      .catch(() => {
        ElMessage.info('已取消删除');
      })
}

// 添加状态变更处理方法
const handleStatusChange = async (seat) => {
  try {
    // 调用API更新用户状态
    await apiClient.put('/seat/edit', {
      id: seat.id,
      status: seat.status
    });
    ElMessage.success('状态更新成功');
  } catch (error) {
    console.error('状态更新失败:', error);
    ElMessage.error('状态更新失败: ' + (error.response?.data?.msg || error.message));      // 如果更新失败，回滚状态
    seat.status = seat.status === 1 ? 0 : 1;
  }
}

// 新增区域选项数据（添加到script setup中）
const areaOptions = ref([
  { label: 'VIP区', value: 'VIP区' },
  { label: 'A区', value: 'A区' },
  { label: 'B区', value: 'B区' },
  { label: '内场', value: '内场' },
  { label: '看台', value: '看台' }
]);


</script>

<template>
  <!--搜索-->
  <el-form :inline="true" :model="searchObj" class="demo-form-inline" style="margin-top: 10px">
<!--    <el-form-item label="演唱会编号">-->
<!--      <el-input v-model="searchObj.concertid" placeholder="请输入演唱会编号" clearable />-->
<!--    </el-form-item>-->
    <el-form-item label="区域">
      <el-input v-model="searchObj.area" placeholder="请输入区域" clearable />
    </el-form-item>
  </el-form>
  <el-form :inline="true">
    <el-form-item>
      <el-button type="primary" @click="handleSearch" style="background-color: #c5a7df; border-color: #c5a7df;">查询</el-button>
    </el-form-item>
    <el-form-item >
      <el-button type="primary" @click="handleAdd" style="background-color: #c5a7df; border-color: #c5a7df;">新增</el-button>
    </el-form-item>
  </el-form>

  <el-table
      :data="Array.isArray(tableData) ? tableData : []"
      style="width: 100%"
      height="tableHeight"
      v-loading="tableData.length === 0 && total === 0">
    <el-table-column fixed prop="id" label="序号" width="100" />
    <el-table-column prop="concertTitle" label="演唱会编号" width="160" />
    <el-table-column prop="area" label="区域" width="160" />
    <el-table-column prop="count" label="票数" width="160" />
    <el-table-column prop="capacity" label="容量" width="100" />
    <el-table-column prop="price" label="价格" width="100">
      <template #default="scope">
        <span>{{ scope.row.price || '无价格' }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="status" label="状态" width="100" >
      <template #default="seat">
        <el-switch
            v-model="seat.row.status"
            inline-prompt
            class="状态"
            width="60"
            active-text="售空"
            inactive-text="可售"
            :active-value="1"
            :inactive-value="0"
            active-color="#67c23a"
            inactive-color="#f56c6c"
            @change="handleStatusChange(seat.row)"
        >
        </el-switch>
      </template>
    </el-table-column>
    <!--    <el-table-column prop="createtime" label="创建时间" width="160" />-->
    <!--    <el-table-column prop="isdel" label="是否删除" width="100" />-->
    <el-table-column label="处理按钮">
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
          编辑
        </el-button>
        <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)" >
          删除
        </el-button>
      </template>
    </el-table-column>



  </el-table>
  <!--分页-->
  <el-pagination
      v-model:current-page="searchObj.current"
      v-model:page-size="searchObj.limit"
      :page-sizes="[10, 20, 30, 40]"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"

  />



  <!--   编辑对话框-->

  <el-dialog v-model="editWinVisible" title="编辑" width="500">
    <el-form :model="obj" label-width="100px">
      <el-form-item label="演唱会编号" class="">
        <el-input v-model="obj.concertTitle" placeholder="演唱会编号" clearable />
      </el-form-item>
      <el-form-item label="区域">
        <el-select v-model="obj.area" placeholder="请选择区域" clearable>
          <el-option
              v-for="item in areaOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="票数">
        <el-input v-model="obj.count" placeholder="票数" clearable />
      </el-form-item>
      <el-form-item label="容量">
        <el-input v-model="obj.capacity" placeholder="容量" clearable />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editCancel">取消</el-button>
        <el-button type="primary" @click="editCommit ">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>

</template>

<style scoped>

</style>